package com.rad.statistics.android;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.rad.datastat.utils.Utils;
import com.rad.statistics.common.BaseEvent;
import com.rad.statistics.common.cmd.StatisticsCmd;

/**
 * 类说明：设置指定的{@link BaseEvent}
 * 对象或其子类的一些特殊属性（包括Event产生时间、经纬度和网络状态），并转化为相应格式的JSON的数据
 * 
 * @author jie.li
 * @date 2014-10-16
 * @version 1.0
 */
public class EventFormat {

	/**
	 * 设置指定的{@link BaseEvent}对象或其子类的一些属性，并转化为相应格式的JSON的数据，并返回
	 * {@link StatisticsCmd}对象
	 * 
	 * @param event
	 * @return {@link StatisticsCmd}对象
	 */
	public static StatisticsCmd onFormat(Context context, BaseEvent event) {

		if (TextUtils.isEmpty(event.getEventName())) {
			throw new IllegalArgumentException(
					"event's eventName must not be null");
		}

		// 设置Event数据
		setEventLocationInfo(context, event);
		event.setNetworkEnvironment(getNetworkInfo(context));
		event.setDate(System.currentTimeMillis());

		// 将Event转化成JSON数据
		Gson gson = new Gson();
		String eventJsonStr = gson.toJson(event);

		ArrayList<String> datas = new ArrayList<String>();
		datas.add(eventJsonStr);

		// 设置StatisticsCmd的数据
		StatisticsCmd cmd = new StatisticsCmd();
		getPhoneInfo(context, cmd);
		cmd.setDatas(datas);
		return cmd;
	}

	// 设置点击事件的定位信息
	private static void setEventLocationInfo(Context context, BaseEvent event) {
		double latitude = 0.0;
		double longitude = 0.0;
		try {
			LocationManager loctionManager = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
			List<String> matchingProviders = loctionManager.getAllProviders();
			for (String prociderString : matchingProviders) {
				Location location = loctionManager
						.getLastKnownLocation(prociderString);
				if (location != null) {
					latitude = location.getLatitude();
					longitude = location.getLongitude();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		event.setLatitude(latitude);
		event.setLongitude(longitude);
	}

	// 设置手机的基本信息
	private static void getPhoneInfo(Context context, StatisticsCmd cmd) {
		TelephonyManager tManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		cmd.setIMEI(tManager.getDeviceId());
		cmd.setIMSI(tManager.getSubscriberId());
		cmd.setPhoneType(getPhoneTypeName());
		cmd.setOsVersion(android.os.Build.VERSION.RELEASE);
		cmd.setPixel(getScreenDensity(context));
		cmd.setMacAddress(getMacAddress(context));
		cmd.setOsPlatforms("android");
		cmd.setSystemApp(isSystemApp(context));
		cmd.setBrand(Utils.getBrand());
		cmd.setNetworkType(Utils.getNetworkInfo(context)[0]);
	}
	
	private static boolean isSystemApp(Context context){
        return (context.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) == 1;
	}

	/**
	 * 获取手机的生产商和名称
	 * 
	 * @return 手机的生产商和名称
	 */
	public static String getPhoneTypeName() {
		String manufacturer = Build.MANUFACTURER;
		String model = Build.MODEL;

		if (model.startsWith(manufacturer)) {
			return model;
		} else {
			return manufacturer + " " + model;
		}
	}

	/**
	 * 获取手机的分辨率
	 * 
	 * @param context
	 * @return “width x height”形式的字符串
	 */
	public static String getScreenDensity(Context context) {
		WindowManager wManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics dMetrics = new DisplayMetrics();

		wManager.getDefaultDisplay().getMetrics(dMetrics);
		int width = dMetrics.widthPixels;
		int height = dMetrics.heightPixels;

		return width + "x" + height;
	}

	/**
	 * 获取手机的MAC地址
	 * 
	 * @param context
	 * @return MAC地址
	 */
	public static String getMacAddress(Context context) {
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String macAddr = wifiInfo.getMacAddress();
		return macAddr;
	}

	/**
	 * 获取当前网络状态
	 * 
	 * @param context
	 * @return 有网络的情况下，返回当前网络状态；无网络的情况下，返回0-length的字符串
	 */
	public static String getNetworkInfo(Context context) {
		String netTypeName = "";
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connManager.getActiveNetworkInfo();

		if (networkInfo != null && networkInfo.getState() == State.CONNECTED) {
			if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
				netTypeName = networkInfo.getSubtypeName();
			} else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				netTypeName = networkInfo.getTypeName();
			}
		}

		return netTypeName;
	}
}
